package response;

import client.CtfState;
import protocol.CtfActionException;
import structures.Position;
import utils.Conversions;

/**
 * Represents the server response to a CONNECT message type (1).
 * 		Player ID	
 * 			 0	Error
 * 			 +	Player ID in Game
 */
public class ConnectBody {
	public static final int LENGTH = 2;
	
	/* Fields set */
	int idInGame;
	
	/* Derived fields */
	int team;
	int idOnTeam;
	
	public int getIdInGame() { return idInGame; }
	public int getTeam() { return team; }
	public int getIdOnTeam() { return idOnTeam; }
	
	/**
	 * Parses the received byte array. (Client usage)
	 * 
	 * @param response
	 * @throws CtfActionException
	 */
	public ConnectBody( byte[] response ) throws CtfActionException {
		idInGame = Conversions.bytesToInt(response);
		if ( idInGame == -1 )
			throw new CtfActionException("1:connect");
		team = calculateTeam( idInGame );
		idOnTeam = calculateIdOnTeam( idInGame );
		
		/***************** Instantiate State ******************/
		new CtfState( idInGame, team );
	}
	
	/**
	 * Set ID in game field. (Server usage)
	 * @param idInGame
	 */
	public ConnectBody( int idInGame ) {
		this.idInGame = idInGame;
	}
	
	/**
	 * Convert ID in game field to a byte array in network byte order. 
	 * (Server usage)
	 * @return byte array
	 */
	public byte[] toNetworkByteArray() {
		return Conversions.intToBytes(idInGame);
	}
	
	/* Client determines team and ID on team from ID in game 
	 * 		Team 1: even (including 0) 
	 * 		Team 2: odd										 */
	int calculateTeam( int idInGame ) {
		return ( idInGame % 2 ) + 1;
	}
	
	/* Client determines ID on team from ID in game */
	int calculateIdOnTeam( int idInGame ) {
		return ( idInGame + 1 ) / 2;
	}
}